package com.gotcha.bootstart.restful;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

import javax.annotation.Resource;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

//@Transactional//测试完成后对数据库的操作回滚,不建议使用,因为实现注解的方法是在内存中进行的,与实际不符
@Slf4j
//@RunWith(SpringRunner.class),Junit4的，构建了一个servlet容器，可以使用注入的Bean
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
//@SpringBootTest//单独使用此注解不会启动servlet容器,使用@Resource@Autowired进行注入,会注入null
@WebMvcTest//加载controller层
public class ArticleRestControllerTest3 {

    @Resource
    private MockMvc mockMvc;

    //@MockBean//打桩，用来伪造service
    /*@Before
    public void setUp() {
        mockMvc = MockMvcBuilders.standaloneSetup(new ArticleRestController()).build();
    }*/

    @Test
    public void saveArticle() throws Exception {

        String article = "{\n" +
                "    \"id\": 1,\n" +
                "    \"author\": \"gotcha\",\n" +
                "    \"title\": \"springboot-start\",\n" +
                "    \"content\": \"c\",\n" +
                "    \"createTime\": \"2020-05-18 15:23:34\",\n" +
                "    \"reader\":[{\"name\":\"gotcha\",\"age\":18},{\"name\":\"kobe\",\"age\":37}]\n" +
                "}";
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.request(HttpMethod.POST, "/rest/article")
                .contentType("application/json").content(article))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.author").value("gotcha"))
                .andExpect(MockMvcResultMatchers.jsonPath("$.data.reader[0].age").value(18))
                .andDo(print())
                .andReturn();
        //perform方法,模拟请求
        //andExpect方法,添加RequestMatcher验证规则
        //andDo,添加RequestHandlerj结果处理器
        //andReturn,最后返回相应的MvcResult

        log.info(result.getResponse().getContentAsString());

    }
}